<script setup lang="ts">
import { getCurrentInstance, ref, reactive, onMounted } from 'vue'
import { onBeforeRouteLeave } from 'vue-router'
const { proxy } = getCurrentInstance()

/* ---- */
const userInfo = proxy.$Store.get('userInfo') || {}
const WXConfig = proxy.$Store.get('WXConfig') || {}
const forSys = proxy.$Sys || []

/* --设置微信分享功能-- */
proxy.$WxTool.loadJsdk(WXConfig, (obj) => {
  if (!obj) return
  // ----
  obj.hideMenuItem()
})

/* ---- */
const load = reactive({
  add: true,
  maxnum: 1,
  forFree: 9 / 5,
  setTrueStyle: {},
  imgs: [],
  option: {
    viewMode: 0,
    dragMode: 'move',
    autoCropArea: 1,
    center: false,
    cropBoxMovable: false,
    cropBoxResizable: false,
    toggleDragModeOnDblclick: false
  },
  cropImg: proxy.$Global.cropImg
})
const avatar = reactive({
  add: true,
  maxnum: 1,
  forFree: 1,
  setTrueStyle: {},
  imgs: [],
  option: {
    viewMode: 0,
    dragMode: 'move',
    aspectRatio: 1,
    autoCropArea: 1,
    center: false,
    cropBoxMovable: false,
    cropBoxResizable: false,
    toggleDragModeOnDblclick: false
  },
  cropImg: proxy.$Global.cropImg
})
const logo = reactive({
  add: true,
  maxnum: 1,
  forFree: 1,
  setTrueStyle: {},
  imgs: [],
  option: {
    viewMode: 0,
    dragMode: 'move',
    aspectRatio: 1,
    autoCropArea: 1,
    center: false,
    cropBoxMovable: false,
    cropBoxResizable: false,
    toggleDragModeOnDblclick: false
  },
  cropImg: proxy.$Global.cropImg
})
const ewm = reactive({
  add: true,
  maxnum: 1,
  forFree: 1,
  setTrueStyle: {},
  imgs: [],
  option: {
    viewMode: 0,
    dragMode: 'move',
    aspectRatio: 1,
    autoCropArea: 1,
    center: false,
    cropBoxMovable: false,
    cropBoxResizable: false,
    toggleDragModeOnDblclick: false
  },
  cropImg: proxy.$Global.cropImg
})
// ----
const myCityData = proxy.$City
// ----
let globalData = {}
// ----
const isNumber = /^\d+(\.{0,2}\d+){0,2}$/
const isMobile = /^(1[3456789]\d{9})$/
const form = reactive({
  id: 0,
  tabName: 'market_service',
  // ----
  siteName: '',
  companyName: '',
  companyDesc: '',
  emptyName: '',
  emptyDesc: '',
  shareName: '',
  shareDesc: '',
  telphone: '',
  addrCity: '',
  // ----
  clubPageName: '',
  clubShareName: '',
  clubShareDesc: '',
  // ----
  lookNum: '',
  releaseNum: ''
})

/* ---- */
const pickerCity = ref()
const uploadoss = ref()
const layer = ref()
const layerLoading = ref()

/* ---- */
const getFormInfo = () => {
  load.setTrueStyle = { height: `${document.querySelector('.loadBox dl dd label').clientWidth / load.forFree}px` }
  avatar.setTrueStyle = { height: `${document.querySelector('.avatarBox dl dd label').clientWidth / avatar.forFree}px` }
  logo.setTrueStyle = { height: `${document.querySelector('.squareBox dl dd label').clientWidth / logo.forFree}px` }
  ewm.setTrueStyle = { height: `${document.querySelector('.powerBox dl dd label').clientWidth / ewm.forFree}px` }
  // --获取信息--
  const newItems = forSys.filter((item) => { return String(item.name) === form.tabName })
  if (Number(newItems.length) === 1) {
    form.id = newItems[0].id
    proxy.$Myfun.getJsonData(newItems[0].value, (resJson) => {
      const RJData = resJson[0] || {}
      globalData = RJData
      // ----
      if (RJData.site_title) form.siteName = RJData.site_title
      if (RJData.company_title) form.companyName = RJData.company_title
      if (RJData.company_desc) form.companyDesc = RJData.company_desc
      if (RJData.empty_title) form.emptyName = RJData.empty_title
      if (RJData.empty_desc) form.emptyDesc = RJData.empty_desc
      if (RJData.share_title) form.shareName = RJData.share_title
      if (RJData.share_desc) form.shareDesc = RJData.share_desc
      if (RJData.telphone) form.telphone = RJData.telphone
      // ----
      let forCity = ''
      if (RJData.district) {
        forCity = RJData.province + ' - ' + RJData.city + ' - ' + RJData.district
      } else if (RJData.city) {
        forCity = RJData.province + ' - ' + RJData.city
      } else if (RJData.province) {
        forCity = RJData.province
      }
      form.addrCity = forCity
      // ----
      if (RJData.club_page_title) form.clubPageName = RJData.club_page_title
      if (RJData.club_share_title) form.clubShareName = RJData.club_share_title
      if (RJData.club_share_desc) form.clubShareDesc = RJData.club_share_desc
      // ----
      if (RJData.look_num) form.lookNum = RJData.look_num
      if (RJData.release_num) form.releaseNum = RJData.release_num
      // ----
      RJData.load.forEach((item) => {
        load.imgs.push({
          imgName: item.name,
          imgUrl: item.image,
          imgW: item.width,
          imgH: item.height
        })
      })
      if (Number(load.imgs.length) >= Number(load.maxnum) && Number(load.maxnum) > 0) load.add = !load.add
        // ----
      RJData.avatar.forEach((item) => {
        avatar.imgs.push({
          imgName: item.name,
          imgUrl: item.image,
          imgW: item.width,
          imgH: item.height
        })
      })
      if (Number(avatar.imgs.length) >= Number(avatar.maxnum) && Number(avatar.maxnum) > 0) avatar.add = !avatar.add
      // ----
      RJData.logo.forEach((item) => {
        logo.imgs.push({
          imgName: item.name,
          imgUrl: item.image,
          imgW: item.width,
          imgH: item.height
        })
      })
      if (Number(logo.imgs.length) >= Number(logo.maxnum) && Number(logo.maxnum) > 0) logo.add = !logo.add
      // ----
      RJData.wechat_img.forEach((item) => {
        ewm.imgs.push({
          imgName: item.name,
          imgUrl: item.image,
          imgW: item.width,
          imgH: item.height
        })
      })
      if (Number(ewm.imgs.length) >= Number(ewm.maxnum) && Number(ewm.maxnum) > 0) ewm.add = !ewm.add
    })
  }
}
// --上传图片操作--
const uploadAct = (type, selectObj, event, index) => {
  const uploadOss = uploadoss.value
  switch (Number(type)) {
    case 1: {
      uploadOss.uploadImg(event, selectObj,'imgs', index)
      break
    }
    case 2: {
      uploadOss.delInfo(selectObj, event)
      break
    }
  }
}
// ----
const emptyInfo = (event) => {
  const curEL = event.currentTarget
  const input = curEL.parentElement.querySelector('input')
  input.value = ''
  input.dispatchEvent(new Event('input'))
}
const checkLimit = (event, reg, info) => {
  const curEL = event.currentTarget
  if (Number(curEL.value.length) === 0) return false
  if (!reg.test(curEL.value)) {
    if (info) proxy.$Myfun.forToast(layer.value, 'open', info)
    curEL.value = ''
    curEL.dispatchEvent(new Event('input'))
  }
}
// ----
const getAuditFun = (type) => {
  switch (Number(type)) {
    case 1: {
      const options = {
        type: 3,
        button: ['取消', '确定'],
        initData: myCityData,
        yes: (result) => {
          let resText = ''
          result.forEach((curItem, index) => {
            resText += (index > 0 ? ' - ' : '') + curItem.text
          })
          form.addrCity = resText
        }
      }
      proxy.$Myfun.isIndepth(pickerCity.value, 'open', options)
      break
    }
  }
}
// ----
const subform = async () => {
  if (Number(form.telphone.length) > 0 && !isMobile.test(form.telphone)) {
    proxy.$Myfun.forToast(layer.value, 'open', '请填写合法的手机号！')
    return false
  }
  // ----
  const forCity = form.addrCity.split(' - ')
  // ----
  const loadItems = []
  if (Number(load.imgs.length) > 0) {
    load.imgs.forEach((item, index) => {
      loadItems.push({
        name: item.imgName,
        image: item.imgUrl,
        width: item.imgW,
        height: item.imgH
      })
    })
  }
  // ----
  const avatarItems = []
  if (Number(avatar.imgs.length) > 0) {
    avatar.imgs.forEach((item, index) => {
      avatarItems.push({
        name: item.imgName,
        image: item.imgUrl,
        width: item.imgW,
        height: item.imgH
      })
    })
  }
  // ----
  const logoItems = []
  if (Number(logo.imgs.length) > 0) {
    logo.imgs.forEach((item, index) => {
      logoItems.push({
        name: item.imgName,
        image: item.imgUrl,
        width: item.imgW,
        height: item.imgH
      })
    })
  }
  // ----
  const ewmItems = []
  if (Number(ewm.imgs.length) > 0) {
    ewm.imgs.forEach((item, index) => {
      ewmItems.push({
        name: item.imgName,
        image: item.imgUrl,
        width: item.imgW,
        height: item.imgH
      })
    })
  }
  // ----
  globalData.site_title = form.siteName
  globalData.company_title = form.companyName
  globalData.company_desc = form.companyDesc
  globalData.empty_title = form.emptyName
  globalData.empty_desc = form.emptyDesc
  globalData.share_title = form.shareName
  globalData.share_desc = form.shareDesc
  globalData.load = loadItems
  globalData.avatar = avatarItems
  globalData.logo = logoItems
  globalData.telphone = form.telphone
  globalData.province = forCity[0]
  globalData.city = forCity[1]
  globalData.district = forCity[2]
  globalData.wechat_img = ewmItems
  // ----
  globalData.club_page_title = form.clubPageName
  globalData.club_share_title = form.clubShareName
  globalData.club_share_desc = form.clubShareDesc
  // ----
  globalData.look_num = form.lookNum
  globalData.release_num = form.releaseNum
  // ----
  const forValue = JSON.stringify(globalData)
  // ----
  let forType = 'post'
  let forUrl = 'system/create'
  let forData = {
    name: form.tabName,
    value: forValue,
    // ----
    config_id: userInfo.config_id,
    openid: userInfo.openid
  }
  if (Number(form.id) > 0) {
    forType = 'patch'
    forUrl = 'system/update?id=' + form.id
    forData = {
      value: forValue,
      // ----
      config_id: userInfo.config_id,
      openid: userInfo.openid
    }
  }
  // ----
  proxy.$Myfun.onLoading(layerLoading.value, 'open', proxy.$Global.loadingMsg)
  let resData = ''
  await proxy.$http[forType](forUrl, forData).then((res) => { resData = res }).catch((err) => { proxy.$Myfun.forToast(layer.value, 'open', err) })
  // ----
  proxy.$Myfun.disLoading(layerLoading.value, 'close')
  if (resData) proxy.$router.back()
}
const goback = () => { proxy.$router.back() }

/* ---- */
onMounted(() => {
  getFormInfo()
})
onBeforeRouteLeave(() => { proxy.$Myfun.setScrollTop(proxy.$refs.formSection) })
</script>

<template>
  <div class="mescroll-touch" ref="formSection">
    <div class="formSet">
      <ul>
        <li>
          <div class="form-txt xw-radius-3 xw-flex xw-flex-align">
            <i>项目名称</i>
            <p class="xw-flex-W1"><input class="text" type="text" placeholder="" v-model.trim="form.siteName"/></p>
            <transition name="fade"><em class="fa fa-times-circle" @click="emptyInfo" v-if="form.siteName"></em></transition>
          </div>
        </li>
        <li>
          <div class="form-imgs xw-radius-3 loadBox">
            <div class="FIS-top xw-flex xw-flex-align xw-flex-justify">
              <span class="FIS-title">加载图片</span>
            </div>
            <dl class="FIS-img">
              <dd v-for="(item, index) in load.imgs"><label class="xw-block xw-act"><img :src="item.imgUrl"/><input type="file" style="display: none;" accept="image/*" @change="uploadAct(1, load, $event, index)"/></label><span class="FIS-del fal fa-times xw-act" @click="uploadAct(2, load, index)"></span></dd>
              <dd v-if="load.add"><label class="xw-act xw-flex xw-flex-center" :style="load.setTrueStyle"><em class="fal fa-plus"></em><input type="file" style="display: none;" accept="image/*" @change="uploadAct(1, load, $event)"/></label></dd>
            </dl>
          </div>
        </li>
        <li>
          <div class="form-are xw-radius-3">
            <h1>默认公司标题（商务中心）</h1>
            <p><textarea class="tarea-H3" placeholder="" v-model.trim="form.companyName"></textarea></p>
          </div>
        </li>
        <li>
          <div class="form-are xw-radius-3">
            <h1>默认公司描述（商务中心）</h1>
            <p><textarea class="tarea-H3" placeholder="" v-model.trim="form.companyDesc"></textarea></p>
          </div>
        </li>
        <li>
          <div class="form-imgs xw-radius-3 avatarBox">
            <div class="FIS-top xw-flex xw-flex-align xw-flex-justify">
              <span class="FIS-title">默认用户头像</span>
            </div>
            <dl class="FIS-img">
              <dd v-for="(item, index) in avatar.imgs"><label class="xw-block xw-act"><img :src="item.imgUrl"/><input type="file" style="display: none;" accept="image/*" @change="uploadAct(1, avatar, $event, index)"/></label><span class="FIS-del fal fa-times xw-act" @click="uploadAct(2, avatar, index)"></span></dd>
              <dd v-if="avatar.add"><label class="xw-act xw-flex xw-flex-center" :style="avatar.setTrueStyle"><em class="fal fa-plus"></em><input type="file" style="display: none;" accept="image/*" @change="uploadAct(1, avatar, $event)"/></label></dd>
            </dl>
          </div>
        </li>
        <li>
          <div class="form-are xw-radius-3">
            <h1>默认标题为空提示（商务信息）</h1>
            <p><textarea class="tarea-H3" placeholder="" v-model.trim="form.emptyName"></textarea></p>
          </div>
        </li>
        <li>
          <div class="form-are xw-radius-3">
            <h1>默认描述为空提示（商务信息）</h1>
            <p><textarea class="tarea-H3" placeholder="" v-model.trim="form.emptyDesc"></textarea></p>
          </div>
        </li>
        <li>
          <div class="form-are xw-radius-3">
            <h1>默认分享标题</h1>
            <p><textarea class="tarea-H3" placeholder="" v-model.trim="form.shareName"></textarea></p>
          </div>
        </li>
        <li>
          <div class="form-are xw-radius-3">
            <h1>默认分享描述</h1>
            <p><textarea class="tarea-H3" placeholder="" v-model.trim="form.shareDesc"></textarea></p>
          </div>
        </li>
        <li>
          <div class="form-imgs xw-radius-3 squareBox">
            <div class="FIS-top xw-flex xw-flex-align xw-flex-justify">
              <span class="FIS-title">默认LOGO</span>
            </div>
            <dl class="FIS-img">
              <dd v-for="(item, index) in logo.imgs"><label class="xw-block xw-act"><img :src="item.imgUrl"/><input type="file" style="display: none;" accept="image/*" @change="uploadAct(1, logo, $event, index)"/></label><span class="FIS-del fal fa-times xw-act" @click="uploadAct(2, logo, index)"></span></dd>
              <dd v-if="logo.add"><label class="xw-act xw-flex xw-flex-center" :style="logo.setTrueStyle"><em class="fal fa-plus"></em><input type="file" style="display: none;" accept="image/*" @change="uploadAct(1, logo, $event)"/></label></dd>
            </dl>
          </div>
        </li>
        <li>
          <div class="form-txt xw-radius-3 xw-flex xw-flex-align">
            <i>默认电话</i>
            <p class="xw-flex-W1"><input class="text" placeholder="" v-model.trim="form.telphone"/></p>
            <transition name="fade"><em class="fa fa-times-circle" @click="emptyInfo" v-if="form.telphone"></em></transition>
          </div>
        </li>
        <li>
          <div class="form-imgs xw-radius-3 powerBox">
            <div class="FIS-top xw-flex xw-flex-align xw-flex-justify">
              <span class="FIS-title">默认二维码</span>
            </div>
            <dl class="FIS-img">
              <dd v-for="(item, index) in ewm.imgs"><label class="xw-block xw-act"><img :src="item.imgUrl"/><input type="file" style="display: none;" accept="image/*" @change="uploadAct(1, ewm, $event, index)"/></label><span class="FIS-del fal fa-times xw-act" @click="uploadAct(2, ewm, index)"></span></dd>
              <dd v-if="ewm.add"><label class="xw-act xw-flex xw-flex-center" :style="ewm.setTrueStyle"><em class="fal fa-plus"></em><input type="file" style="display: none;" accept="image/*" @change="uploadAct(1, ewm, $event)"/></label></dd>
            </dl>
          </div>
        </li>
        <li>
          <div class="form-txt xw-radius-3 xw-flex xw-flex-align">
            <i>默认地区</i>
            <p class="xw-flex-W1"><input class="text" type="text" placeholder="" v-model="form.addrCity" @click="getAuditFun(1)" readonly unselectable="on" onfocus="this.blur()"/></p>
            <span class="fa fa-caret-down xw-color-16"></span>
            <transition name="fade"><em class="fa fa-times-circle" @click="emptyInfo" v-if="form.addrCity"></em></transition>
          </div>
        </li>
        <li>
          <div class="form-are xw-radius-3">
            <h1>【商务中心】页面标题</h1>
            <p><textarea class="tarea-H3" placeholder="" v-model.trim="form.clubPageName"></textarea></p>
          </div>
        </li>
        <li>
          <div class="form-are xw-radius-3">
            <h1>【商务中心】分享标题</h1>
            <p><textarea class="tarea-H3" placeholder="" v-model.trim="form.clubShareName"></textarea></p>
          </div>
        </li>
        <li>
          <div class="form-are xw-radius-3">
            <h1>【商务中心】分享描述</h1>
            <p><textarea class="tarea-H3" placeholder="" v-model.trim="form.clubShareDesc"></textarea></p>
          </div>
        </li>
        <li>
          <div class="form-txt xw-radius-3 xw-flex xw-flex-align">
            <i>默认查看成员次数</i>
            <p class="xw-flex-W1"><input class="text" placeholder="" v-model.trim="form.lookNum" @blur="checkLimit($event, isNumber, '请输入非负数')"/></p>
            <transition name="fade"><em class="fa fa-times-circle" @click="emptyInfo" v-if="form.lookNum"></em></transition>
          </div>
        </li>
        <li>
          <div class="form-txt xw-radius-3 xw-flex xw-flex-align">
            <i>默认发布商机次数</i>
            <p class="xw-flex-W1"><input class="text" placeholder="" v-model.trim="form.releaseNum" @blur="checkLimit($event, isNumber, '请输入非负数')"/></p>
            <transition name="fade"><em class="fa fa-times-circle" @click="emptyInfo" v-if="form.releaseNum"></em></transition>
          </div>
        </li>
      </ul>
      <div class="form-sub xw-radius-3 xw-bgCL-11 xw-act" @click="subform">确定提交</div>
      <div class="form-sub xw-radius-3 xw-WhiteRed xw-act" @click="goback">取消返回</div>
    </div>
    <picker-view ref="pickerCity"/>
    <uploadoss-view ref="uploadoss"/>
    <layer-view ref="layer"/>
    <layer-view ref="layerLoading"/>
  </div>
</template>
